/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package RSSReader;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.oauth.j2me.*;
import net.oauth.j2me.token.*;

/**
 *
 * @author pothead
 */
public class Twitter {

    AccessToken at = null;
    Consumer consumer = null;
    String lastResponse = "";

    public String getLastResponse()
    {
        String errMsg = "";
        int errPos = lastResponse.indexOf("<errors>");
        errPos = lastResponse.indexOf("<error", errPos == -1? 0: errPos + "<errors>".length());
        errPos = lastResponse.indexOf(">", errPos);
        if (errPos != -1)
        {
            int endErr = lastResponse.indexOf("</error>");
            errMsg = "Fehler: ";
            errMsg += lastResponse.substring(errPos + 1, endErr == -1 ? lastResponse.length() : endErr);
           
        } else
        {
            errMsg = lastResponse;
        }
        return errMsg;
    }

    public void login() throws net.oauth.j2me.OAuthServiceProviderException, BadTokenStateException
    {
        consumer = new Consumer("TwnDPNLU30c6Tca8oz4hA","r2SimMfmN7J4ErmnJTzPrbVgoGXEsmM9ObdMh3GRE");
        System.out.println("Get Request Token...");
         RequestToken rtoken = consumer.getRequestToken("http://api.twitter.com/oauth/request_token");
         //rtoken.
         System.out.println("Request Token:");
         //System.out.println(rtoken.toString());
         at = consumer.getAccessToken("http://twitter.com/oauth/access_token", rtoken);

    }

    public boolean twitterMsg(String msg) throws OAuthServiceProviderException, IOException
    {
        boolean ret = false;
        Hashtable hashTable = new Hashtable();
       // hashTable.put(new Integer(1), "POST");
        hashTable.put(new Integer(2), "Das ist ein Test");
        consumer.accessProtectedResource("", at, hashTable);
        ret = true;
        return ret;
    }

    public boolean twitterMsg(String msg, String userName, String passWord) throws IOException
    {
        boolean ret = false;
        HttpConnection con = null;
        DataInputStream dis = null;
        OutputStream os = null;
        int rc;
        try {
        con = (HttpConnection)Connector.open("http://api.twitter.com/1/statuses/update.xml", Connector.READ_WRITE);
        con.setRequestMethod("POST");
        con.setRequestProperty("Authorization", "Basic " + Util.base64Encode((userName + ":" + passWord).getBytes()));
        os = con.openOutputStream();
        if (os != null)
        {
            os.write(("status="+msg).getBytes());
            rc = con.getResponseCode();
            // Get the length and process the data
            int len = con.getHeaderFieldInt("Content-Length", 0);

            System.out.println("content-length="+len);
            dis = con.openDataInputStream();

            byte[] data = null;
            if (len == -1L) {
                System.out.println("no content");
                ByteArrayOutputStream tmp = new ByteArrayOutputStream();
                int ch;
                while( ( ch = dis.read() ) != -1 ) {
                    tmp.write( ch );
                }
                data = tmp.toByteArray();
            } else {
                data = new byte[len];
                dis.read(data);
            }
            lastResponse=new String(data);
            if (rc == HttpConnection.HTTP_OK)
            {
                ret = true;
                System.out.println("OK");
            } else
            {
                System.out.println("Http response Code: " + String.valueOf(rc) );
                System.out.println(lastResponse);
            }

        }
         } catch (ClassCastException e) {
            throw new IllegalArgumentException("Not an HTTP URL");
        } finally {
            if (dis != null)
                dis.close();
            if (con != null)
                con.close();
        }

        return ret;
  }

    public void logout()
    {

    }

    public boolean isLoggedIn()
    {
        return at == null ? false : at.getAuthorized();
    }
}
